package kpi.java_training.domain.teaching;

import kpi.java_training.domain.questions.Question;
import kpi.java_training.domain.questions.QuestionData;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Alex Kebkalo on 12.11.13.
 * class implements list of questions
 */
public class TeachingQuestionList {
    private final int NOT_FOUND = -1;
    private List<SameComplexityQuestions> questions;

    public TeachingQuestionList() {
        questions = new LinkedList<>();
    }

    public int getComplexity(int index) {
        if (inRange(index)) {
            return questions.get(index).getComplexity();
        } else {
            return NOT_FOUND;
        }
    }

    public int getBucketSize(int index) {
        if (inRange(index)) {
            return questions.get(index).getBucketSize();
        } else {
            return NOT_FOUND;
        }
    }

    public void add(Question item) {
        int index = findQuestionsByComplexity(item.getComplexity());
        if (index == NOT_FOUND) {
            SameComplexityQuestions sameQuestions = new SameComplexityQuestions(item.getComplexity());
            index = size();
            questions.add(sameQuestions);
        }
        questions.get(index).add(item);
    }

    public int size() {
        return questions.size();
    }

    public int findQuestionsByComplexity(int complexity) {
        int i=0;
        while (i < size()) {
            if (questions.get(i).getComplexity() == complexity) {
                return i;
            }
            i++;
        }
        return NOT_FOUND;
    }

    public boolean parseUserAnswer(int index, String userAnswer) {
        if (inRange(index)) {
            return questions.get(index).parseUserAnswer(userAnswer);
        }
        return false;
    }

    public String getQuestionMessage(int index) {
        if (inRange(index)) {
            return questions.get(index).getQuestionMessage();
        } else {
            return "";
        }
    }

    public QuestionData getQuestionData(int index) {
        if (inRange(index)) {
            return questions.get(index).getQuestionData();
        } else {
            return null;
        }
    }

    private boolean inRange(int questionNumber) {
        return (questionNumber >= 0) && (questionNumber < questions.size());
    }

    public void sortByComplexity() {
        Collections.sort(questions, new QuestionComplexityComparator());
    }

    public void remove(int index) {
        if (inRange(index)) {
            questions.remove(index);
        }
    }
}
